package com.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.db.common.annotation.RequiredUser;
import com.db.common.pojo.PageObject;
import com.db.common.util.ShiroUtiles;
import com.db.dao.SysDeptDao;
import com.db.dao.SysUserDao;
import com.db.dao.SysUserRoleDao;
import com.db.pojo.SysUser;
import com.db.pojo.SysUserRole;
import com.db.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Transactional
@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysDeptDao sysDeptDao;

	@Autowired
	private SysUserRoleDao sysUserRoleDao;

	@RequiredUser(operation = "查询用户")
	@Override
	public PageObject<SysUser> findObjects(String username, Integer pageCurrent) {
		QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
		wrapper.orderByDesc("modifiedTime");
		if (!StringUtils.isEmptyOrWhitespace(username)) {
			wrapper.like("username", username);
		}
		IPage<SysUser> page = new Page<>(pageCurrent, 7);
		IPage<SysUser> iPage = sysUserDao.selectPage(page, wrapper);
		List<SysUser> records = iPage.getRecords();

		for (SysUser sysUser :
				records) {
			sysUser.setSysDept(sysDeptDao.selectById(sysUser.getDeptId())); //将部门封装进user
		}

		return new PageObject<SysUser>(iPage.getCurrent(), (int) iPage.getSize(), iPage.getTotal(), iPage.getPages(), records);
	}

	@RequiresPermissions("sys:user:update")
	@RequiredUser(operation = "禁用/启用用户")
	@Override
	public void updateValid(Integer id, Integer valid) {

		SysUser sysUser = new SysUser();
		sysUser.setId(id);
		sysUser.setValid(valid);
		sysUserDao.updateById(sysUser); //更新禁用/启用
	}

	@RequiresPermissions("sys:user:add")
	@RequiredUser(operation = "新增用户")
	@Override
	public void insertObject(SysUser sysUser, Integer[] roleIds) {

		String uuid = UUID.randomUUID().toString();

		SimpleHash sh = new SimpleHash("MD5", sysUser.getPassword(), uuid, 1);
		String newPassword = sh.toHex();
		sysUser.setSalt(uuid);
		sysUser.setPassword(newPassword);

		//用户表插入数据
		sysUserDao.insert(sysUser);

		//角色表插入数据
		sysUserRoleDao.insertObject(sysUser.getId(), roleIds);
	}

	@RequiredUser(operation = "查询单个用户")
	@Override
	public Map<String, Object> findById(Integer id) {
		SysUser sysUser = sysUserDao.selectById(id);
		sysUser.setSysDept(sysDeptDao.selectById(sysUser.getDeptId())); //将部门封装进user

		QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
		sysUserRoleQueryWrapper.in("user_id", sysUser.getId());
		List<SysUserRole> sysUserRoles = sysUserRoleDao.selectList(sysUserRoleQueryWrapper);
		Integer[] ins = new Integer[sysUserRoles.size()];
		for (int i = 0; i < ins.length; i++) {
			ins[i] = sysUserRoles.get(i).getRole_id();
		}

		Map<String, Object> map = new HashMap<>();
		map.put("user", sysUser);
		map.put("roleIds", ins);

		return map;
	}

	@RequiresPermissions("sys:user:update")
	@RequiredUser(operation = "更新用户")
	@Override
	public void updateObject(SysUser sysUser, Integer[] roleIds) {
		sysUserDao.updateById(sysUser);

		QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", sysUser.getId());
		//删除中间表
		sysUserRoleDao.delete(wrapper);

		//插入中间表
		sysUserRoleDao.insertObject(sysUser.getId(), roleIds);
	}

	@RequiredUser(operation = "修改密码")
	@Override
	public void updatePassWord(String pwd, String newPwd, String cfgPwd) {

		if (StringUtils.isEmptyOrWhitespace(pwd))
			throw new IllegalArgumentException("原密码不能为空");
		if (StringUtils.isEmptyOrWhitespace(newPwd))
			throw new IllegalArgumentException("新密码不能为空");
		if (!cfgPwd.equals(newPwd))
			throw new IllegalArgumentException("两次密码输入不一致");

		/* 查询当前密码 */
		SysUser user = ShiroUtiles.getUser();
		String salt = user.getSalt();
		SimpleHash simpleHash = new SimpleHash("MD5", pwd, salt, 1);
		if (!user.getPassword().equals(simpleHash.toHex()))
			throw new IllegalArgumentException("输入的原密码不正确");

		/* 修改密码 */
		String uuid = UUID.randomUUID().toString();
		String md5 = new SimpleHash("MD5", newPwd, uuid, 1).toHex();
		user.setPassword(md5);
		user.setSalt(uuid);
		sysUserDao.updateById(user);

	}
}
